// pages/marketing/seckill/seckill.js
var util = require('../../../../utils/util') //引入配置接口文件
import {
  mmsSeckillcurrent,
  mmsSeckillsoon,
  addSubscribe,
  abolishSubscribe
} from '../../../../config/config'
var configUrl = require('../../../../config/config') //引入配置接口文件
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', //足迹全局id
    reGuid: false, //是否onshow判断是否重新生成的guid
    imgUrl: getApp().globalData.imgUrl,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    percentage: '90',
    listCur: 0,
    tabData: [{
      id: 0,
      name: '正在疯抢',
    }, {
      id: 1,
      name: '即将开始',
    }],
    listData: [],
    listDataShow: false,
    show: false,
    currentPage: 1,
    currentRows: 10,
    currentnomoreData: false,
    openid: '',
    addrCode: {},
    titleHeight: '',
    /**-合伙人--*/
    isShowPartnerAll: 1,
    showPartnerCodePop: false,
    authorizationPopup: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.getLogin((re)=>{
      if(!re){
        this.setData({
          authorizationPopup: true
        })
      }
    })
    this.setData({
      footprintGuid: util.guid(),
      reGuid: false
    })
    console.log(options)
    let that = this
    wx.getSystemInfo({
      success(res) {
        let statusBarHeight = res.statusBarHeight + 65
        let listMargintop = res.statusBarHeight + 65 + 59
        that.setData({
          titleHeight: statusBarHeight + 'px',
          listMargintop: listMargintop + 'px'
        })
      }
    })
    let loginMsg = wx.getStorageSync('loginMsg')
    let addrCode = wx.getStorageSync('addrCode')
    that.setData({
      openid: loginMsg.openid,
      addrCode: addrCode
    })
    if (options.hid) {
      var hid = options.hid
        var stInFun = setInterval(() => {
          if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
            clearInterval(stInFun)
            app.bindingPartner(hid)
          }
        }, 1000)
    }
    if (options.status == 'unStart') {
      this.setData({
        listCur : 1
      })
      this.getmmsSeckillsoon()
    }else{
      this.setData({
        listCur : 0
      })
      this.getmmsSeckillcurrent()
    }
  },
  bindGetUserInfo: function (e) { //登录-注册
    var that=this;
    app.getUserInfo()
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
    var setFun=setInterval(()=>{
      if(wx.getStorageSync('showGetPhone')){
        that.setData({
          getPhoneNumberData:{
            isShowGetPhoneNumber:true, 
          },
          showSetting: false,
          isShowGetUserInfo: false
        })
        wx.removeStorageSync('showGetPhone')
        clearInterval(setFun)
      }
    },1000)
    
  },
  onCloseShowGetUserInfo() { //关闭弹出层
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
   /**绑定手机号 ---str*/
   closeGetphone(){
    this.setData({
      getPhoneNumberData:{
        isShowGetPhoneNumber:false

      }
    })
  },
  getPhoneNumber(e){
    var that=this;
    let loginMsg = wx.getStorageSync('loginMsg')
    if (e.detail.iv && e.detail.encryptedData) {
      let option = {}
      option.encryptedData = e.detail.encryptedData
      option.iv = e.detail.iv
      option.openid = loginMsg.openid
      option.session_key = loginMsg.session_key
      app.reqFun.requestJson('POST',configUrl.decryptGetPhone,option,(res)=>{
        if(res.data.success==1){
          that.setData({
            getPhoneNumberData:{
              isShowGetPhoneNumber:false,
            }
          })
          wx.showToast({
            title: '绑定成功。',
          })
        }
      }) 
    } else {
      console.log('取消')
    }
  },
  /**  end
   *  绑定手机号
   */
  onRemind(e) {
    let seckillId = e.currentTarget.dataset.data.id
    let skuId = e.currentTarget.dataset.data.skuId
    let that = this
    let tempIds = []
    // 秒杀开始提醒
    let seckillStart = app.globalData.msgTemplateMap['activityStart']
    let seckillTempId = seckillStart.msgTemplateId
    tempIds.push(seckillTempId)
    wx.requestSubscribeMessage({
      tmplIds: tempIds,
      success(res) {
        if (res[seckillTempId] == "accept") {
          that.appointmentReminder(seckillId, skuId)
        } else {
          console.log('失败')
        }
      },
      fail(res) {
        console.log('订阅出错', res)
        wx.showToast({
          title: '订阅消息发送失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  cancelRemind(e) {
    let seckillId = e.currentTarget.dataset.data.id
    let skuId = e.currentTarget.dataset.data.skuId
    this.notappointmentReminder(seckillId, skuId)
  },
  // 预约消息提醒
  appointmentReminder(seckillId, skuId) {
    let params = {
      activityType: 'seckill',
      activityId: seckillId,
      skuId: skuId,
      userOpId: this.data.openid
    }
    app.reqFun.requestJson('POST', addSubscribe, params, (res) => {
      if (res.data.success === 1) {
        wx.showToast({
          title: '提醒成功',
          icon: 'success',
          duration: 2000
        })
        this.setData({
          listData: [],
          currentPage: 1,
          currentRows: 10,
          currentnomoreData: false
        })
        if (this.data.listCur == 0) {
          this.getmmsSeckillcurrent()
        } else {
          this.getmmsSeckillsoon()
        }
      }
    })
  },
  // 取消预约消息提醒
  notappointmentReminder(seckillId, skuId) {
    let params = {
      activityType: 'seckill',
      activityId: seckillId,
      skuId: skuId,
      userOpId: this.data.openid
    }
    app.reqFun.requestJson('POST', abolishSubscribe, params, (res) => {
      if (res.data.success === 1) {
        this.setData({
          listData: [],
          currentPage: 1,
          currentRows: 10,
          currentnomoreData: false
        })
        if (this.data.listCur == 0) {
          this.getmmsSeckillcurrent()
        } else {
          this.getmmsSeckillsoon()
        }
      }
    })
  },
  listSelect(e) {
    this.setData({
      listCur: e.currentTarget.dataset.id,
      listData: [],
      currentPage: 1,
      currentRows: 10,
      currentnomoreData: false
    })
    if (this.data.listCur == 0) {
      this.getmmsSeckillcurrent()
    } else {
      this.getmmsSeckillsoon()
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.getmmsSeckillcurrent()
  },
  goHome: function (e) { //返回主页
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    if (this.data.reGuid) {
      //第二次onshow时重新生成guid
      this.setData({
        footprintGuid: util.guid()
      })
    } else {
      //第一次onshow
      this.setData({
        reGuid: true
      })
    }
  },

  // 获取正在疯抢
  getmmsSeckillcurrent() {
    let that = this
    console.log('请求数据哈哈2')
    var stInFun = setInterval(() => {
      if (wx.getStorageSync('addrCode').provinceCode) {
        clearInterval(stInFun)
        let code = that.data.addrCode.provinceCode
        let formdata = {}
        formdata.page = that.data.currentPage
        formdata.rows = that.data.currentRows
        formdata.uuid = that.data.footprintGuid
        let mmsSeckillcurrentUrl = mmsSeckillcurrent + '/' + code
        app.reqFun.requestForm('POST', mmsSeckillcurrentUrl, formdata, (res) => {
          if (res.data.success == 1) {
            let records = res.data.data.records
            if (records.length < that.data.currentRows) {
              that.setData({
                currentnomoreData: true
              })
            }
            that.setData({
              listData: that.data.listData.concat(records)
            })
            if(that.data.listData.length == 0) {
              that.setData({
                listDataShow: true
              })
            } else {
              that.setData({
                listDataShow: false
              })
            }
          }
        })
      }else{
        wx.showToast({
          title: '未获取到定位地址，请先登录',
          icon:'none',
          duration:1000
        })
      }
    }, 1000)
  },
  // 获取即将开始
  getmmsSeckillsoon() {
    let that = this
    let code = that.data.addrCode.provinceCode
    let formdata = {}
    formdata.page = that.data.currentPage
    formdata.rows = that.data.currentRows
    formdata.uuid = that.data.footprintGuid
    let mmsSeckillsoonUrl = mmsSeckillsoon + '/' + code
    app.reqFun.requestForm('POST', mmsSeckillsoonUrl, formdata, (res) => {
      if (res.data.success == 1) {
        let records = res.data.data.records
        for (var i = 0, len = records.length; i < len; i++) {
          let startTime = records[i].startTime.split(' ')
          let dateTime = startTime[0].split('-')
          let dateTime1 = startTime[1].split(':')
          records[i].dateTime = dateTime[1] + '月' + dateTime[2] + '日' + dateTime1[0] + ':' + dateTime1[1]
        }
        if (records.length < that.data.currentRows) {
          that.setData({
            currentnomoreData: true
          })
        }
        that.setData({
          listData: that.data.listData.concat(records)
        })
        if(that.data.listData.length == 0) {
          that.setData({
            listDataShow: true
          })
        } else {
          that.setData({
            listDataShow: false
          })
        }
      }
    })
  },
  // 立即抢购
  buyNow(option) {
    // if (this.data.listCur == 0) {
    let skuid = option.currentTarget.dataset.skuid
    wx.navigateTo({
      url: '/packageShop/pages/goodsInfo/goodsInfo?id=' + skuid,
    })
    // }
  },
  goreBack(e) {
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('下拉')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.listCur == 0) {
      if (!this.data.currentnomoreData) {
        this.setData({
          currentPage: this.data.currentPage + 1
        })
        this.getmmsSeckillcurrent()
      }
    } else {
      if (!this.data.currentnomoreData) {
        this.setData({
          currentPage: this.data.currentPage + 1
        })
        this.getmmsSeckillsoon()
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '限时秒杀',
      desc: '限时秒杀',
      path: '/packagBuy/pages/marketing/seckill/seckill?hid=' + wx.getStorageSync('loginMsg').userId
    }
  },
  //展开合伙人信息
  showPartnerAll: function () {
    let isShowPartnerAll;
    if (this.data.isShowPartnerAll == 1) {
      isShowPartnerAll = 0;
    } else {
      isShowPartnerAll = 1;
    }
    this.setData({
      isShowPartnerAll: isShowPartnerAll,
    })
  },
  //展示合伙人二维码
  partnerCode: function (e) {
    // this.setData({
    //   showPartnerCodePop: true,
    // })
    let codeImg=e.target.dataset.url
    wx.previewImage({
      urls:[codeImg],
      current: codeImg, // 当前显示图片的http链接
     })
  },
  //关闭合伙人二维码
  closeCodePop: function () {
    console.log("3253456678dsgudkdkgfksfvkjdsvbjkdsvbvkj")
    this.setData({
      showPartnerCodePop: false,
    })
  },
  //拨打合伙人电话
  partnerPhone: function () {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },
})